<script setup>
	import {reactive, ref} from "vue";
	import productApi from "@/api/product/product.js";
	import newProductApi from "@/api/product/newProduct.js";
	import {ElMessage, ElMessageBox} from "element-plus";
	import {Delete, Plus, Download, Upload, Message, Edit, Search} from "@element-plus/icons-vue";
	
	const list = ref([])
	const total = ref(0)
	
	//分页信息和搜索条件
	const newProductQuery = reactive({
		name: '',
		page: 1,
		limit: 10
	})
	
	//表格数据
	const loadData = () => {
		newProductApi.list(newProductQuery).then(result => {
			list.value = result.data.records
			total.value = result.data.total
		})
	}
	
	loadData()
	
	//搜索
	const onSearch = () => {
		newProductQuery.page = 1
		loadData()
	}
	
	//单个删除
	const deleteById = (id) => {
		ElMessageBox.confirm(
			'确认删除吗?',
			'警告',
			{
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning',
				lockScroll: false   //锁定滚动条。防止抖动
			}
		)
			.then(() => {
				newProductApi.deleteById(id).then(result => {
					if (result.code === 0) {
						ElMessage({message: result.msg, type: 'success',})
					} else {
						ElMessage.error(result.msg)
					}
					//刷新表格
					loadData()
				})
			})
	}
	
	//批量删除
	const ids = ref([])
	const handleSelectionChange = (rows) => {
		ids.value = rows.map(row => row.id)
	}
	const deleteAll = () => {
		ElMessageBox.confirm(
			'确认删除吗?',
			'警告',
			{
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning',
				lockScroll: false   //锁定滚动条。防止抖动
			}
		)
			//点击确认删除
			.then(() => {
				ids.value = ids.value.join(',')
				newProductApi.deleteAll(ids.value).then(result => {
					if (result.code === 0) {
						ElMessage({message: result.msg, type: 'success',})
					} else {
						ElMessage.error(result.msg)
					}
					//刷新表格
					loadData()
				})
			})
	}
	
	//添加、编辑
	const dialogFormVisible = ref(false)
	const newProduct = ref({})
	const title = ref()
	
	//点击"添加"
	const showAddDialog = () => {
		dialogFormVisible.value = true
		title.value = '添加'
		newProduct.value = {}
	}
	//点击"编辑"
	const showUpdateDialog = (id) => {
		dialogFormVisible.value = true
		title.value = '编辑'
		newProduct.value = {}
		newProductApi.selectById(id).then(result => {
			newProduct.value = result.data
		})
	}
	//确认按钮
	const addOrUpdate = () => {
		if (newProduct.value.id) {  //有值，编辑
			newProductApi.update(newProduct.value).then(result => {
				if (result.code === 0) {
					ElMessage({message: result.msg, type: 'success',})
					dialogFormVisible.value = false
				} else {
					ElMessage.error(result.msg)
				}
				//刷新表格
				loadData()
			})
		} else {   //无值，添加
			newProductApi.add(newProduct.value).then(result => {
				if (result.code === 0) {
					ElMessage({message: result.msg, type: 'success',})
					dialogFormVisible.value = false
				} else {
					ElMessage.error(result.msg)
				}
				//刷新表格
				loadData()
			})
		}
	}
	
	//更改状态
	const handleSwitchChange = (row) => {
		newProductApi.updateStatus(row.id, row.status).then(result => {
			if (result.code === 0) {
				ElMessage.success(result.msg)
			} else {
				ElMessage.error(result.msg)
			}
		})
	}
	
	import {useTokenStore} from '@/store/token.js'
	const tokenStore = useTokenStore();
	const headers = ref({
		//携带token传递到后端
		Authorization: tokenStore.token
	});
	
	//上传单个图片成功后
	const handleAvatarSuccess = (result) => {
		newProduct.value.image = result.data
	}
	
	//重置按钮
	const originData = () => ({
		name: "",
		beginUpdateTime: null,
		endUpdateTime: null
	});
	const resetForm = () => {
		Object.assign(newProductQuery, originData());
		loadData();
	};
</script>

<template>
	<el-card class="">
		<template #header>
			<div class="header">
				<el-button type="success" :icon="Plus" @click="showAddDialog">添加</el-button>
				<el-button type="danger" :icon="Delete" @click="deleteAll">批量删除</el-button>
			</div>
		</template>
		<el-form :inline="true">
			<el-form-item label="商品名称">
				<el-input v-model="newProductQuery.name" placeholder="请输入商品名称" clearable/>
			</el-form-item>
			<el-form-item label="更新时间">
				<el-date-picker
					v-model="newProductQuery.beginUpdateTime"
					type="datetime"
					value-format="YYYY-MM-DD HH:mm:ss"
					placeholder="开始时间"
				/>
				-
				<el-date-picker
					v-model="newProductQuery.endUpdateTime"
					type="datetime"
					value-format="YYYY-MM-DD HH:mm:ss"
					placeholder="结束时间"
				/>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" :icon="Search" @click="onSearch">搜索</el-button>
				<el-button @click="resetForm" round>重置</el-button>
			</el-form-item>
		</el-form>
		<el-table :data="list" style="width: 100%" stripe border ref="multipleTableRef"
				  @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center"/>
			<el-table-column fixed="left" sortable prop="id" label="ID" align="center"/>
			<el-table-column prop="name" label="新品名称" width="160" align="center"/>
			<el-table-column prop="image" label="轮播大图" align="center">
				<template #default="scope">
					<img :src="scope.row.image" style="max-height: 40px; max-width: 120px;"/>
				</template>
			</el-table-column>
			<el-table-column prop="status" label="大图状态" align="center" width="130">
				<template #default="scope">
					<el-switch
						v-model="scope.row.status"
						class="ml-2"
						inline-prompt
						size="large"
						active-text="上架"
						:active-value="1"
						inactive-text="下架"
						:inactive-value="0"
						@change="handleSwitchChange(scope.row)"
					/>
				</template>
			</el-table-column>
			<el-table-column prop="updateTime" label="更新时间" align="center" width="200"/>
			<el-table-column fixed="right" label="操作" min-width="200" align="center">
				<template #default="{row}">
					<el-button type="warning" :icon="Edit" round @click="showUpdateDialog(row.id)">编辑</el-button>
					<el-button type="danger" :icon="Delete" round @click="deleteById(row.id)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			v-model:current-page="newProductQuery.page"
			v-model:page-size="newProductQuery.limit"
			:page-sizes="[5, 10, 15, 20]"
			:size="size"
			:disabled="disabled"
			:background="background"
			layout="total, sizes, prev, pager, next, jumper"
			:total="total"
			@change="loadData"
			style="margin-top: 20px; justify-content: flex-end"
		/>
	</el-card>
	
	<!--添加、编辑弹出框-->
	<el-dialog v-model="dialogFormVisible" :title="title" width="70%" :lock-scroll="false">
		<el-form :model="newProduct">
			<el-form-item label="商品名称：" :label-width="100">
				<el-input v-model="newProduct.name" autocomplete="off"/>
			</el-form-item>
			<el-form-item label="新品轮播大图：" :label-width="100">
				<el-upload
					class="avatar-uploader"
					action="/api/product/upload"
					:show-file-list="false"
					:on-success="handleAvatarSuccess"
					:headers="headers"
				>
					<img v-if="newProduct.image" :src="newProduct.image" class="avatar"/>
					<el-icon v-else class="avatar-uploader-icon">
						<Plus/>
					</el-icon>
				</el-upload>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="dialogFormVisible = false">取消</el-button>
				<el-button type="primary" @click="addOrUpdate">
					确认
				</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<style scoped>
	.avatar-uploader .avatar {
		width: 178px;
		height: 178px;
		display: block;
	}
	
</style>
<style>
	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}
	
	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}
	

</style>